package conf

import (
	"encoding/json"
	"fmt"
	"github.com/pkg/errors"
	"io"
	"net/http"
	"strings"
)

type ConfApi struct {
	apiKey      string
	secretKey   string
	authUrl     string
	accessToken string
	OCRUrl      string
	//TextTransUrl string
}

// SetKey 设置 API 密钥以及 Secret 密钥
func (c *ConfApi) SetKey(apiKey, secretKey string) (err error) {
	c.apiKey = apiKey
	c.secretKey = secretKey
	c.accessToken, err = c.requestAccessToken()
	if err != nil {
		return
	}
	if c.accessToken == "" {
		return errors.New("不合法的 keys")
	}
	c.OCRUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + c.accessToken
	//c.TextTransUrl = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + c.accessToken
	return
}

// requestAccessToken 获取 AccessToken
func (c *ConfApi) requestAccessToken() (string, error) {
	postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", c.apiKey, c.secretKey)
	resp, err := http.Post(c.authUrl, "application/x-www-form-urlencoded", strings.NewReader(postData))
	if err != nil {
		return "", err
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	accessTokenObj := map[string]string{}
	_ = json.Unmarshal(body, &accessTokenObj)
	return accessTokenObj["access_token"], err
}
